package com.runa.monitor.platinterface.meter3_0.session;

import com.runa.monitor.platinterface.meter3_0.handle.ResponseBusinessHandler;
import com.runa.monitor.platinterface.meter3_0.task.TaskProxy;
import com.runa.monitor.platinterface.backwork.function.TaskFunction;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import javax.websocket.Session;
import java.util.Map;

/**
 * @author diandian
 * @Date 2022/11/20 15:32
 */
@Getter
@Setter
@AllArgsConstructor
public class SessionProxy {
    private Session session;

    private SessionState sessionState;

    //标记，一般用网络设备号来做标记
    private String identity;

    public SessionProxy(Session session, SessionState sessionState, String identity) {
        this.session = session;
        this.sessionState = sessionState;
        this.identity = identity;
    }

    private TaskProxy taskProxy;

    public void setTaskProxy(TaskProxy taskProxy) {
        this.taskProxy = taskProxy;
    }

    //当状态是send，receive则会有值，当状态是free时，则无值
    private String sendMsg;

    //当状态是receive，则会有值，当状态是free时，则无值
    private String receiveMsg;

    //响应数据处理，当状态是send,则必须要有值，因为现在是一问一答模式
    public void setResponseBusinessHandler(ResponseBusinessHandler responseBusinessHandler) {
        Map<String, Object> userProperties = this.session.getUserProperties();
        userProperties.put(SessionKey.resultHandler.name(), responseBusinessHandler);
    }

    public void setTaskFunction(TaskFunction function) {
        this.session.getUserProperties().put(SessionKey.taskId.name(), function);
    }

    public enum SessionKey {
        taskId,
        resultHandler,
    }

    public enum SessionState {
        //发送完数据
        send,
        //接受到响应数据，正在处理数据中
        receive,
        //响应数据处理结束，还没发送数据，空闲中
        free,
    }


    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("\"session\":")
                .append(session);
        sb.append(",\"sessionState\":")
                .append(sessionState);
        sb.append(",\"identity\":\"")
                .append(identity).append('\"');
        sb.append(",\"taskProxy\":")
                .append(taskProxy);
        sb.append(",\"sendMsg\":\"")
                .append(sendMsg).append('\"');
        sb.append(",\"receiveMsg\":\"")
                .append(receiveMsg).append('\"');
        sb.append('}');
        return sb.toString();
    }
}